import { Dep } from "./dep"

function get<T extends object>(target:T, expr:string) {
  return expr.split('.').reduce((prev, key)=>{
    return Reflect.get(prev, key) as any
  }, target)
}

let id = 0

export class Watcher {
  private oldVal
  private callback
  private uid = id++

  constructor(target:object, expr:string, callback:Function) {
    Dep.active = this
  
    try {
      this.oldVal = get(target, expr)
      // TODO ...
      // render view template

    } catch {}

    Dep.active = null
    this.callback = callback
  }

  // 数据变化时更新视图
  update() {
    const newVal = get({}, '')
    newVal !== this.oldVal && this.callback.call(this, newVal)
  }
}

